package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * ES文章分页搜索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1.设置查询条件
        SearchRequest searchRequest = getSearchRequest(dto);
        // 2.返回结果的数据封装
        List<Map<String, Object>> list = handlerResponse(searchRequest);
        // 3.返回结果
        return ResponseResult.okResult(list);
    }

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insertDocToMongo(String keyword, Integer userId) {
        // 1.根据keyword查询mongo
        ApUserSearch search = mongoTemplate.findOne(Query.query(
                Criteria.where("userId").is(userId)
                        .and("keyword").is(keyword)
        ), ApUserSearch.class);
        // 2.查询有数据
        if (search != null) {
            // 更新创建时间
            search.setCreatedTime(new Date());
            mongoTemplate.save(search);
            return;
        }
        // 3.查询全部搜索词历史记录集合（根据创建时间降序）
        List<ApUserSearch> searches = mongoTemplate.find(Query.query(
                Criteria.where("userId").is(userId)
        ).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        // 4.集合长度小于10
        search = new ApUserSearch();
        search.setUserId(userId);
        search.setKeyword(keyword);
        search.setCreatedTime(new Date());
        if (searches == null || searches.size() < 10) {
            // 插入数据
            mongoTemplate.insert(search);
        } else {
            // 5.集合长度大于等于10
            // 替换最后一条数据
            mongoTemplate.findAndReplace(Query.query(
                    Criteria.where("id").is(searches.get(searches.size() - 1).getId())
            ), search);
        }
    }

    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(
                Criteria.where("userId").is(user.getId())
        ).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除搜索历史
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        mongoTemplate.remove(Query.query(
                Criteria.where("id").is(dto.getId())
                        .and("userId").is(user.getId())
        ), ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 处理响应结果
     *
     * @param searchRequest
     * @return
     * @throws IOException
     */
    private List<Map<String, Object>> handlerResponse(SearchRequest searchRequest) throws IOException {
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = response.getHits().getHits();
        List<Map<String, Object>> list = new ArrayList<>();
        if (hits != null && hits.length > 0) {
            for (SearchHit hit : hits) {
                Map<String, Object> resultMap = hit.getSourceAsMap();
                if (hit.getHighlightFields().size() > 0) {
                    Text[] titles = hit.getHighlightFields().get("title").fragments();
                    if (titles.length > 0) {
                        resultMap.put("h_title", titles[0].toString());
                    }
                } else {
                    resultMap.put("h_title", resultMap.get("title"));
                }
                list.add(resultMap);
            }
        }
        return list;
    }

    /**
     * 设置查询条件
     *
     * @param dto
     * @return
     */
    private SearchRequest getSearchRequest(UserSearchDto dto) {
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 关键词查询
        if (StringUtils.isNotEmpty(dto.getSearchWords())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", dto.getSearchWords()));
            ApUser user = ApThreadLocalUtil.getUser();
            if (user != null) {
                insertDocToMongo(dto.getSearchWords(), user.getId());
            }
        }
        // 小于最大时间
        if (dto.getMinBehotTime() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lte(dto.getMinBehotTime()));
        }
        searchRequest.source().query(boolQueryBuilder);
        // 分页查询
        if (dto.getPageNum() != null && dto.getPageSize() != null) {
            searchRequest.source().from(dto.getPageNum()).size(dto.getPageSize());
        }
        // 按发布时间降序
        searchRequest.source().sort("publishTime", SortOrder.DESC);
        // 高亮显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false).field("title")
                .preTags("<font style='color: red; font-size: inherit;'>")
                .postTags("</font>");
        searchRequest.source().highlighter(highlightBuilder);
        return searchRequest;
    }
}
